from fastapi import Request
from sqlmodel import SQLModel
import random
import hashlib
import uuid
from datetime import datetime

import pandas as pd
from io import StringIO

def random_str():
    """
    唯一随机字符串
    :return: str
    """
    only = hashlib.md5(str(uuid.uuid1()).encode(encoding='UTF-8')).hexdigest()
    return str(only)


def format_timestamp(timestamp: int) -> str:
    """将时间戳转换为格式化的日期时间字符串"""
    return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

def random_num(length: int = 5) -> str:
    # The minimum value for the specified length
    min_value = 10 ** (length - 1)
    # The maximum value for the specified length
    max_value = (10 ** length) - 1
    return str(random.randint(min_value, max_value))

def get_ip(request: Request):
    x_forwarded_for = request.headers.get("X-Forwarded-For")
    if x_forwarded_for:
        # 如果使用了多个代理，X-Forwarded-For 可能包含多个 IP，第一个通常是真实的客户端 IP
        client_ip = x_forwarded_for.split(",")[0]
    else:
        client_ip = request.client.host
    return client_ip



async def flatten_data(data: list[dict]) -> list[dict]:
    """Flatten nested dictionaries into a single level dictionary."""
    flattened_data = []
    for item in data:
        flat_item = {}
        for key, value in item.items():
            if isinstance(value, dict):
                # For nested dictionaries, flatten the content
                for sub_key, sub_value in value.items():
                    flat_item[f"{key}.{sub_key}"] = sub_value
            else:
                flat_item[key] = value
        flattened_data.append(flat_item)
    return flattened_data



async def generate_large_csv_from_sqlmodel(data: list[dict]):
    """Generate large CSV data from a SQLModel query."""
    buffer = StringIO()
    chunk_size = 10000
    flattenend_data = await flatten_data(data)
    for i in range(0, len(flattenend_data), chunk_size):
        chunk = flattenend_data[i:i + chunk_size]
        df = pd.DataFrame(chunk)
        df.to_csv(buffer, index=False, header=(i == 0))  # 仅在第一个块写入表头
        buffer.seek(0)
        yield buffer.read()
        buffer.truncate(0)
        buffer.seek(0)


async def convert_to_timestamp(date_str: str) -> int:
    """
    将日期字符串转换为Unix时间戳。
    
    参数:
    date_str (str): 带有时区的日期字符串
    
    返回:
    int:
    """
    # 清理日期字符串，移除多余的 "(China Standard Time)" 部分
    cleaned_date_str = date_str.split(' (')[0]
    
    # 将字符串转换为 datetime 对象
    dt = datetime.strptime(cleaned_date_str, "%a %b %d %Y %H:%M:%S %Z%z")
    
    # 转换为时间戳并返回
    return int(dt.timestamp())